package org.laizili.solution.leetcode;

import java.util.*;

/**
 * <a href="https://leetcode-cn.com/problems/most-common-word/">819. 最常见的单词</a>
 * <p> 简单模拟; 哈希表
 * <p>
 * notes: 注意读题及题目的提示信息; 这道题虽然简单，但细节处理不到位也容易wrong answer
 */
public class Problem819 {
    public static class Solution {
        public String mostCommonWord(String paragraph, String[] banned) {
            Set<String> bannedWord = new HashSet<>(Arrays.asList(banned));
            //String[] words = paragraph.split("[ !?',;.]");
            Map<String, Integer> wordCount = new HashMap<>();
            String res = null;
            int maxCount = 0;
            int length = paragraph.length();
            for (int i = 0; i < length; i++) {
                if (Character.isLetter(paragraph.charAt(i))) {
                    int endIndex = i + 1;
                    while (endIndex < length && Character.isLetter(paragraph.charAt(endIndex))) {
                        endIndex++;
                    }
                    String word = paragraph.substring(i, endIndex).toLowerCase();
                    i = endIndex;
                    // 过滤空串和敏感词（这里不可能出现空串）
                    if (/*word.length() > 0 &&*/ !bannedWord.contains(word)) {
                        wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
                        if (wordCount.get(word) > maxCount) {
                            // 更新结果
                            res = word;
                            maxCount = wordCount.get(word);
                        }
                    }
                }
            }
            return res;
        }

    }
}
